<!-- 设备管理-设备列表页面 -->
<template>
  <div>
    <div v-show="drawerType === 'LIST'" class="equip-wrap-common">
      <px-form ref="queryRef" class="custom-form-ui equip-form" :model="queryParams" inline label-width="120px">
        <px-row :gutter="12">
          <px-col :span="6">
            <px-form-item label="设备ID/名称">
              <px-input
                v-model="queryParams.value"
                placeholder="请输入设备ID/名称"
                maxlength="50"
                clearable
                @blur="queryParams.value = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <px-col :span="6">
            <EquipSystemTree
              :className="queryParams.className"
              :systemCode="queryParams.systemCode"
              @changeAllSystemCodes="changeAllSystemCodes"
              @changeSystemCodes="changeSystemCodes"
              @clearSystem="clearSystem"
            />
          </px-col>
          <px-col :span="6">
            <EquipCategorySelect
              :className="queryParams.className"
              :systemCodes="systemCodes"
              :categoryId="queryParams.categoryId"
              @changeCategory="changeCategory"
            />
          </px-col>
          <px-col :span="6">
            <EquipTypeSelect
              :className="queryParams.className"
              :systemCodes="systemCodes"
              :categoryId="queryParams.categoryId"
              :typeId="queryParams.typeId"
              @changeType="changeType"
            />
          </px-col>
          <px-col :span="6">
            <EquipModelSelect
              :className="queryParams.className"
              :systemCodes="systemCodes"
              :categoryId="queryParams.categoryId"
              :typeId="queryParams.typeId"
              :modelId="queryParams.modelId"
              @changeModel="changeModel"
            />
          </px-col>
          <px-col :span="6">
            <px-form-item label="设备位置" prop="positionCodes">
              <px-cascader
                ref="cascaderRef"
                v-model="queryParams.positionCodes"
                filterable
                clearable
                style="width: 100%"
                :options="positionList"
                :props="defaultProps"
                placeholder="请选择设备位置"
                @change="cascaderRef.togglePopperVisible()"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" style="margin-right: 8px" @click="queryTable">查询</px-button>
            <px-button style="margin-right: 8px" @click="resetQuery">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="flex-row">
        <div class="flex-row-item" style="display: flex">
          <px-button v-has="'ALL_EQUIP_ARCHIVE_LIST_ADD'" type="primary" style="margin-right: 8px" @click="handleAdd">新增设备</px-button>
          <px-button v-has="'ALL_EQUIP_ARCHIVE_LIST_DOWNLOAD'" style="margin-right: 8px" type="primary" plain @click="templateDownload">
            下载模板
          </px-button>
          <BatchUpload url="/ifp/digitaltwins/api/v1/equipment/importEqp" permission="ALL_EQUIP_ARCHIVE_LIST_IMPORT" @updateUploadPage="queryTable" />
          <px-button v-has="'ALL_EQUIP_ARCHIVE_LEDGER_BATCH_DOWNLOAD'" type="primary" plain style="margin-right: 8px" @click="batchDownload">
            查询并导出
          </px-button>
          <px-button v-has="'ALL_EQUIP_ARCHIVE_LEDGER_EXPORT_EQPIMG'" type="success" plain style="margin-right: 8px" @click="batchDownloadEqpImg">
            查询并导出设备标签
          </px-button>
          <px-button v-has="'ALL_EQUIP_ARCHIVE_LEDGER_RECREATE'" type="warning" plain style="margin-right: 8px" @click="isEqpImgShow = true">
            设备标签重新生成
          </px-button>
        </div>
        <div class="flex-row-item">
          <px-dropdown trigger="click" @command="sortTable">
            <px-button icon="ArrowDown">{{ sortArr[sortType - 1].name }}</px-button>
            <template #dropdown>
              <px-dropdown-menu style="margin-left: 0">
                <px-dropdown-item v-for="item in sortArr" :key="item.id" :command="item.value">{{ item.name }}</px-dropdown-item>
              </px-dropdown-menu>
            </template>
          </px-dropdown>
        </div>
      </div>
      <px-table
        v-loading="loading"
        class="equip-table"
        :data="equipTypeList"
        height="calc(100vh - 350px)"
        border
        @selection-change="handleSelectionChange"
      >
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
          </template>
        </px-table-column>
        <px-table-column min-width="180" show-overflow-tooltip label="设备ID" align="center" fixed="left" prop="eqpId" />
        <px-table-column min-width="150" show-overflow-tooltip label="设备名称" align="center" prop="eqpName" />
        <px-table-column min-width="80" show-overflow-tooltip label="科室" align="center" prop="classNameDesc" />
        <px-table-column min-width="150" show-overflow-tooltip label="系统" align="center" prop="systemName" />
        <px-table-column min-width="120" show-overflow-tooltip label="设备总称" prop="categoryName" />
        <px-table-column min-width="120" show-overflow-tooltip label="设备类型" prop="typeName" />
        <px-table-column min-width="120" show-overflow-tooltip label="设备型号" prop="modelName" />
        <px-table-column label="操作" align="center" fixed="right" width="180">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ALL_EQUIP_ARCHIVE_LIST_VIEW'" link icon="Tickets" type="primary" @click="handleDetail(scope.row)" />
            </px-tooltip>
            <px-tooltip content="复制" placement="top">
              <px-button v-has="'ALL_EQUIP_ARCHIVE_LIST_COPY'" link icon="DocumentCopy" type="primary" @click="handleCopy(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'ALL_EQUIP_ARCHIVE_LIST_EDIT'" link icon="EditPen" type="primary" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'ALL_EQUIP_ARCHIVE_LIST_DELETE'" link icon="Delete" type="primary" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        class="equip-table-pagination"
        @pagination="queryTable"
      />
    </div>
    <!-- 新增页面 -->
    <AddEquipPage :eqpId="eqpId" :drawerType="drawerType" @queryTable="queryTable" @backMainPage="backMainPage" />
    <!-- 编辑页面 -->
    <EditEqpPage :eqpId="eqpId" :drawerType="drawerType" @queryTable="queryTable" @backMainPage="backMainPage" />
    <!-- 详情页面 -->
    <EquipDetails :drawerType="drawerType" :tab="tab" :eqpId="eqpId" @backMainPage="backMainPage" />
    <!--设备二维码标签重新生成弹窗-->
    <CreateEqpImgDialog :visible="isEqpImgShow" @closeDialog="isEqpImgShow = false" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_ARCHIVE_LIST"
});
import { deleteEquipment, getEqpImgs, queryEquipLedger } from "@/api/equip/archive";
import { getTableData } from "@/api/system/positionManage";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
import { getToken } from "@/utils/auth";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipModelSelect from "@/views/all/equip/components/EquipModelSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import axios from "axios";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onActivated, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute } from "vue-router";
import AddEquipPage from "./components/AddEquipPage.vue";
import CreateEqpImgDialog from "./components/CreateEqpImgDialog.vue";
import EditEqpPage from "./components/EditEqpPage.vue";
import EquipDetails from "./components/EquipDetails.vue";

const route = useRoute();
const cascaderRef = ref();
const { proxy } = getCurrentInstance();

const tab = ref("");

onActivated(() => {
  if (route.query.eqpId) {
    drawerType.value = "DETAIL";
    eqpId.value = route.query.eqpId;
    if (route.query.tab) {
      tab.value = route.query.tab;
    }
  }
});

onMounted(async () => {
  positionList.value = await getTableData({});
  queryTable();
});

const tagBorderColorList = {
  1: "#3B82F6", // 正常
  2: "#F59E0B", // 带病运行
  3: "#10B981", // 备机
  4: "#EF4444", // 故障
  5: "#909399" // 未上线
};
const tagBgColorList = {
  1: "#EFF6FF",
  2: "#FEF5E6",
  3: "#E8F8F3",
  4: "#FEECEC",
  5: "#F4F4F5"
};

// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  eqpId.value = "";
  drawerType.value = "LIST";
};

const loading = ref(true);
const total = ref(0);
const defaultProps = {
  children: "children",
  label: "name",
  value: "code",
  checkStrictly: true
};
const data = reactive<Record<string, any>>({
  drawerType: "LIST",
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    isAsc: "desc",
    orderByColumn: "updateTime"
  },
  selectIds: [], // 选中的数据
  equipTypeList: [], // 列表数据
  eqpId: "",
  systemCodes: [],
  sortArr: [
    { id: 1, value: 1, name: "按更新时间正序" },
    { id: 2, value: 2, name: "按更新时间倒序" },
    { id: 3, value: 3, name: "按编号正序" },
    { id: 4, value: 4, name: "按编号倒序" },
    { id: 5, value: 5, name: "按类型正序" },
    { id: 6, value: 6, name: "按类型倒序" }
  ],
  positionList: [],
  isEqpImgShow: false,
  sortType: 1 // 当前排序类型
});

const { drawerType, equipTypeList, queryParams, selectIds, eqpId, systemCodes, sortArr, positionList, isEqpImgShow, sortType } = toRefs(data);

const queryTable = async () => {
  try {
    loading.value = true;
    const params = JSON.parse(JSON.stringify(queryParams.value));
    params.systemCodes = systemCodes.value;
    const { positionCodes } = queryParams.value;
    const res = await queryEquipLedger({ ...params, positionCodes: positionCodes ? [positionCodes[positionCodes?.length - 1]] : [] });
    equipTypeList.value = res?.data || [];
    total.value = res?.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

// 表格排序
const sortTable = command => {
  sortType.value = command;
  if (command === 1) {
    queryParams.value.isAsc = "asc";
    queryParams.value.orderByColumn = "updateTime";
  } else if (command === 2) {
    queryParams.value.isAsc = "desc";
    queryParams.value.orderByColumn = "updateTime";
  } else if (command === 3) {
    queryParams.value.isAsc = "asc";
    queryParams.value.orderByColumn = "eqpId";
  } else if (command === 4) {
    queryParams.value.isAsc = "desc";
    queryParams.value.orderByColumn = "eqpId";
  } else if (command === 5) {
    queryParams.value.isAsc = "asc";
    queryParams.value.orderByColumn = "typeId";
  } else if (command === 6) {
    queryParams.value.isAsc = "desc";
    queryParams.value.orderByColumn = "typeId";
  }
  queryTable();
};
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    isAsc: "desc",
    orderByColumn: "updateTime"
  };
  systemCodes.value = [];
  queryTable();
}

/** 新增按钮操作 */
const handleAdd = () => {
  drawerType.value = "ADD";
};
const handleCopy = async row => {
  drawerType.value = "COPY";
  eqpId.value = row.eqpId;
};
const handleDetail = async row => {
  drawerType.value = "DETAIL";
  eqpId.value = row.eqpId;
};

const handleEdit = async row => {
  drawerType.value = "EDIT";
  eqpId.value = row.eqpId;
};
/** 多选框选中数据 */
const handleSelectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.eqpId) {
      selectIds.value.push(item.eqpId);
    }
  });
};

/** 删除按钮操作 */
function handleDelete(row) {
  const { eqpId, eqpName } = row;
  PxMessageBox.confirm(`是否删除设备${eqpName}？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteEquipment({ eqpId });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
}

// 批量下载
const batchDownload = async () => {
  await queryTable();
  const params = {
    value: queryParams.value.value,
    className: queryParams.value.className,
    systemCodes: systemCodes.value,
    categoryId: queryParams.value.categoryId,
    typeId: queryParams.value.typeId,
    eqpRunStatus: queryParams.value.eqpRunStatus
  };
  proxy.download("post", "/digitaltwins/api/v1/equipment/exportEqpData", params, "设备信息.xlsx");
};

// 批量下载设备图片
const batchDownloadEqpImg = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  if (systemCodes.value?.length === 0) {
    PxMessage.warning("文件太大，请先选择系统再下载~");
    return;
  }
  params.systemCodes = systemCodes.value;
  const { positionCodes } = queryParams.value;
  const eqpImgIdList = await getEqpImgs({ ...params, positionCodes: positionCodes ? [positionCodes[positionCodes?.length - 1]] : [] });
  if (eqpImgIdList?.length === 0) {
    PxMessage.warning("没有符合条件的设备二维码标签");
    return;
  }
  if (eqpImgIdList) {
    axios({
      method: "post",
      url: "/ifp/sharing/api/v1/file/downloadFilesAsZip",
      data: {
        idList: eqpImgIdList
      },
      responseType: "blob",
      headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        Authorization: "Bearer " + getToken().accessToken || "",
        facCode: localStorage.getItem("facCode") || ""
      }
    }).then(async res => {
      PxMessage.success("设备二维码标签下载中，请耐心等待~");
      const blob = new Blob([res.data], { type: res.headers["content-Type"] });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "设备二维码标签.zip";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    });
  }
};

// 下载模版
const templateDownload = async () => {
  proxy.download("get", "/digitaltwins/api/v1/equipment/templateDownLoad", {}, "设备信息模版.xlsx");
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  queryParams.value.systemCode = val;
  systemCodes.value = val2;
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  queryParams.value.className = val2;
  queryParams.value.systemCode = val3;
  systemCodes.value = val4;
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 系统组件值改变触发
const clearSystem = val => {
  queryParams.value.systemCode = "";
  systemCodes.value = [];
  queryParams.value.categoryId = null;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 改变设备总称，清空设备类型和设备型号
const changeCategory = val => {
  queryParams.value.categoryId = val;
  queryParams.value.typeId = null;
  queryParams.value.modelId = null;
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  queryParams.value.categoryId = val2;
  queryParams.value.typeId = val;
  queryParams.value.modelId = null;
};
// 改变设备型号
const changeModel = (val, val2, val3) => {
  queryParams.value.categoryId = val2;
  queryParams.value.typeId = val3;
  queryParams.value.modelId = val;
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  .flex-row-item {
    .px-button + .px-button {
      margin-left: 0;
    }
  }
}
</style>
